import { Request, Response } from 'express';
import { Op } from 'sequelize';
import Category from '../models/Category';
import { successResponse, errorResponse } from '../utils/response';
import { asyncHandler } from '../utils/asyncHandler';

class CategoryController {
  /**
   * 创建商品分类
   */
  createCategory = asyncHandler(async (req: Request, res: Response) => {
    const { name, parentId = 0, level = 1, sortOrder = 0, icon, image, description, isShow = 1 } = req.body;

    // 验证父分类是否存在（如果不是顶级分类）
    if (parentId > 0) {
      const parentCategory = await Category.findByPk(parentId);
      if (!parentCategory) {
          return errorResponse(res, '父分类不存在', 400);
        }
        
        if (parentCategory.level >= 3) {
          return errorResponse(res, '分类层级不能超过3级', 400);
        }
    }

    // 检查同级分类名称是否重复
    const existingCategory = await Category.findOne({
      where: {
        name,
        parentId
      }
    });

    if (existingCategory) {
      return errorResponse(res, '同级分类中已存在相同名称的分类', 400);
    }

    const category = await Category.create({
      name,
      parentId,
      level,
      sortOrder,
      icon,
      image,
      description,
      isShow
    });

    return successResponse(res, category, '创建分类成功', 200);
  });

  /**
   * 获取分类列表（支持分页和筛选）
   */
  getCategoryList = asyncHandler(async (req: Request, res: Response) => {
    // 处理前端传递的嵌套params参数
    const queryParams = (req.query as any).params || req.query;
    
    const { 
      page = 1, 
      pageSize = 10, 
      parentId, 
      level, 
      isShow, 
      keyword 
    } = queryParams;

    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    // 构建查询条件
    const whereCondition: any = {};
    
    if (parentId !== undefined) {
      whereCondition.parentId = Number(parentId);
    }
    
    if (level !== undefined) {
      whereCondition.level = Number(level);
    }
    
    if (isShow !== undefined) {
      whereCondition.isShow = Number(isShow);
    }
    
    if (keyword) {
      whereCondition.name = {
        [Op.like]: `%${keyword}%`
      };
    }

    const { count, rows } = await Category.findAndCountAll({
      where: whereCondition,
      order: [['sortOrder', 'ASC'], ['createdAt', 'DESC']],
      offset,
      limit
    });

    const result = {
      list: rows,
      total: count,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(count / Number(pageSize))
    };

    return successResponse(res, result, '获取分类列表成功');
  });

  /**
   * 获取分类树形结构
   */
  getCategoryTree = asyncHandler(async (req: Request, res: Response) => {
    const { isShow } = req.query;

    // 构建查询条件
    const whereCondition: any = {};
    if (isShow !== undefined) {
      whereCondition.isShow = Number(isShow);
    }

    const categories = await Category.findAll({
      where: whereCondition,
      order: [['sortOrder', 'ASC'], ['createdAt', 'ASC']]
    });

    // 构建树形结构
    const buildTree = (parentId: number = 0): any[] => {
      return categories
        .filter((category: any) => category.parentId === parentId)
        .map((category: any) => ({
          ...category.toJSON(),
          children: buildTree(category.id)
        }));
    };

    const tree = buildTree();
    return successResponse(res, tree, '获取分类树成功');
  });

  /**
   * 根据ID获取分类详情
   */
  getCategoryById = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    const category = await Category.findByPk(id);
    if (!category) {
      return errorResponse(res, '分类不存在', 404);
    }

    return successResponse(res, category, '获取分类详情成功');
  });

  /**
   * 更新分类
   */
  updateCategory = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;
    const { name, parentId, level, sortOrder, icon, image, description, isShow } = req.body;

    const category = await Category.findByPk(id);
    if (!category) {
      return errorResponse(res, '分类不存在', 404);
    }

    // 验证父分类是否存在（如果不是顶级分类）
    if (parentId !== undefined && parentId > 0) {
      const parentCategory = await Category.findByPk(parentId);
      if (!parentCategory) {
        return errorResponse(res, '父分类不存在', 400);
      }
      
      // 不能将分类设置为自己的子分类
      if (parentId === Number(id)) {
        return errorResponse(res, '不能将分类设置为自己的子分类', 400);
      }
    }

    // 检查同级分类名称是否重复（排除自己）
    if (name !== undefined) {
      const existingCategory = await Category.findOne({
        where: {
          name,
          parentId: parentId !== undefined ? parentId : category.parentId,
          id: { [Op.ne]: id }
        }
      });

      if (existingCategory) {
        return errorResponse(res, '同级分类中已存在相同名称的分类', 400);
      }
    }

    await category.update({
      name,
      parentId,
      level,
      sortOrder,
      icon,
      image,
      description,
      isShow
    });

    return successResponse(res, category, '更新分类成功');
  });

  /**
   * 删除分类
   */
  deleteCategory = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    const category = await Category.findByPk(id);
    if (!category) {
      return errorResponse(res, '分类不存在', 404);
    }

    // 检查是否有子分类
    const childCount = await Category.count({
      where: { parentId: id }
    });

    if (childCount > 0) {
      return errorResponse(res, '该分类下还有子分类，无法删除', 400);
    }

    // 这里可以添加检查是否有关联的商品
    // const productCount = await Product.count({ where: { categoryId: id } });
    // if (productCount > 0) {
    //   return errorResponse(res, '该分类下还有商品，无法删除', 400);
    // }

    await category.destroy();
    return successResponse(res, null, '删除分类成功');
  });

  /**
   * 批量删除分类
   */
  deleteCategories = asyncHandler(async (req: Request, res: Response) => {
    const { ids } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return errorResponse(res, '请提供要删除的分类ID数组', 400);
    }

    // 检查所有分类是否存在
    const categories = await Category.findAll({
      where: { id: { [Op.in]: ids } }
    });

    if (categories.length !== ids.length) {
      return errorResponse(res, '部分分类不存在', 400);
    }

    // 检查是否有子分类
    const childCount = await Category.count({
      where: { parentId: { [Op.in]: ids } }
    });

    if (childCount > 0) {
      return errorResponse(res, '选中的分类中有包含子分类的，无法删除', 400);
    }

    // 批量删除
    await Category.destroy({
      where: { id: { [Op.in]: ids } }
    });

    return successResponse(res, null, `成功删除${ids.length}个分类`);
  });

  /**
   * 更新分类显示状态
   */
  updateCategoryStatus = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;
    const { isShow } = req.body;

    const category = await Category.findByPk(id);
    if (!category) {
      return errorResponse(res, '分类不存在', 404);
    }

    await category.update({ isShow });
    return successResponse(res, category, '更新分类状态成功');
  });

  /**
   * 获取分类统计信息
   */
  getCategoryStats = asyncHandler(async (req: Request, res: Response) => {
    const totalCount = await Category.count();
    const showCount = await Category.count({ where: { isShow: 1 } });
    const hideCount = await Category.count({ where: { isShow: 0 } });
    
    const levelStats = await Category.findAll({
      attributes: [
        'level',
        [Category.sequelize!.fn('COUNT', Category.sequelize!.col('id')), 'count']
      ],
      group: ['level'],
      raw: true
    });

    const stats = {
      total: totalCount,
      show: showCount,
      hide: hideCount,
      levelStats
    };

    return successResponse(res, stats, '获取分类统计成功');
  });
}

export default new CategoryController();